package com.horizon.mobile.activity;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Timer;
import java.util.TimerTask;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.interfaces.OnBottomDragListener;
import zuo.biao.library.util.SettingUtil;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.widget.ImageView;
import android.widget.Toast;

import com.horizon.mobile.R;
import com.horizon.mobile.manage.SharePreferences;
import com.horizon.mobile.util.EscapeUnescape;
import com.horizon.mobile.util.FilePreviewUtil;
import com.horizon.mobile.util.HttpRequest;
import com.horizon.webview.utils.WebViewJavaScriptFunction;
import com.horizon.webview.utils.X5WebView;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient.CustomViewCallback;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebSettings.LayoutAlgorithm;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.tencent.smtt.utils.TbsLog;

/**
 * 流程详情界面Activity
 * 
 * @author 左大明
 * @use toActivity(FlowDetailActivity.createIntent(...));
 */
public class FlowDetailActivity extends BaseActivity implements
		OnBottomDragListener,WebViewJavaScriptFunction {
	private static final String TAG = "FlowDetailActivity";
	X5WebView mWebView;
	String title;
	String workId;
	String flowId;
	String subjectionId;
	boolean isLoaded=false;
	public static final String WORKID = "WORKID";
	public static final String FLOWID = "FLOWID";
	public static final String FLOWNAME = "FLOWNAME";
	public static final String SUBJECTIONID = "subjectionId";
	private ValueCallback<Uri> uploadFile;
	private ValueCallback<Uri[]> uploadFiles;
	// 启动方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

	/**
	 * 启动这个Activity的Intent
	 * 
	 * @param context
	 * @return
	 */
	public static Intent createIntent(Context context, String workId,
			String flowName, String flowId,String subjectionId) {
		return new Intent(context, FlowDetailActivity.class)
				.putExtra(WORKID, workId).putExtra(FLOWNAME, flowName)
				.putExtra(FLOWID, flowId).putExtra(SUBJECTIONID, subjectionId);
	}

	// 启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

	@Override
	public Activity getActivity() {
		return this;
	}

	@SuppressLint("JavascriptInterface")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.flow_detail_activity, this);
		intent = getIntent();
		//title = intent.getStringExtra(FLOWNAME);
		title="流程详情";
		workId = intent.getStringExtra(WORKID);
		flowId = intent.getStringExtra(FLOWID);
		subjectionId= intent.getStringExtra(SUBJECTIONID);
		// 功能归类分区方法，必须调用<<<<<<<<<<
		initView();
		initData();
		initEvent();
		showProgressDialog("正在加载...");
		progressDialog.setCancelable(true);
		// 功能归类分区方法，必须调用>>>>>>>>>>

	}

	// UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

	private ImageView[] ivSettings;

	@Override
	public void initView() {// 必须调用
		mWebView = (X5WebView) findViewById(R.id.tbsWebView);
		// 设置支持JavaScript脚本

		// System.out.println(url+"&username="+SharedPreferencesUtils.getParam(this,
		// User.ID, "").toString());
		// mWebView.loadUrl(url+"&username="+SharedPreferencesUtils.getParam(this,
		// User.ID, "").toString());
		String token = EscapeUnescape.escape(
				SharePreferences.getInstance(context).getToken()).replaceAll(
				"/\\+/g", "%2B");
		String urlString = HttpRequest.getWebBaseUrl()
				+ "/horizon/workflow/support/open.wf?workId=" + workId
				+ "&flowId=" + flowId + "&accessToken=" + token + "&subjection=" + subjectionId;
		mWebView.loadUrl(urlString);

		mWebView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				return false;
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				// mTestHandler.sendEmptyMessage(MSG_OPEN_TEST_URL);
				/* mWebView.showLog("test Log"); */
			}
		});

		mWebView.setWebChromeClient(new WebChromeClient() {
			// For Android 3.0+
			public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
				Log.i("test", "openFileChooser 1");
				FlowDetailActivity.this.uploadFile = uploadFile;
				openFileChooseProcess();
			}

			// For Android < 3.0
			public void openFileChooser(ValueCallback<Uri> uploadMsgs) {
				Log.i("test", "openFileChooser 2");
				FlowDetailActivity.this.uploadFile = uploadFile;
				openFileChooseProcess();
			}

			// For Android  > 4.1.1
			public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
				Log.i("test", "openFileChooser 3");
				FlowDetailActivity.this.uploadFile = uploadFile;
				openFileChooseProcess();
			}

			// For Android  >= 5.0
			public boolean onShowFileChooser(com.tencent.smtt.sdk.WebView webView,
											 ValueCallback<Uri[]> filePathCallback,
											 WebChromeClient.FileChooserParams fileChooserParams) {
				Log.i("test", "openFileChooser 4:" + filePathCallback.toString());
				FlowDetailActivity.this.uploadFiles = filePathCallback;
				openFileChooseProcess();
				return true;
			}

			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				if (newProgress == 100) {
					dismissProgressDialog();
					isLoaded = true;
					Log.i("打印日志","加载完成");
				}
			}
			@Override
			public boolean onJsConfirm(WebView arg0, String arg1, String arg2,
					JsResult arg3) {
				return super.onJsConfirm(arg0, arg1, arg2, arg3);
			}

			View myVideoView;
			View myNormalView;
			CustomViewCallback callback;

			// /////////////////////////////////////////////////////////
			//

			@Override
			public void onHideCustomView() {
				if (callback != null) {
					callback.onCustomViewHidden();
					callback = null;
				}
				if (myVideoView != null) {
					ViewGroup viewGroup = (ViewGroup) myVideoView.getParent();
					viewGroup.removeView(myVideoView);
					viewGroup.addView(myNormalView);
				}
			}

			@Override
			public boolean onJsAlert(WebView arg0, String arg1, String arg2,
					JsResult arg3) {
				/**
				 * 这里写入你自定义的window alert
				 */
				return super.onJsAlert(null, arg1, arg2, arg3);
			}
		});

		mWebView.setDownloadListener(new DownloadListener() {

			@Override
			public void onDownloadStart(String arg0, String arg1, String arg2,
					String arg3, long arg4) {
				TbsLog.d(TAG, "url: " + arg0);
				new AlertDialog.Builder(FlowDetailActivity.this)
						.setTitle("allow to download？")
						.setPositiveButton("yes",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										Toast.makeText(
												FlowDetailActivity.this,
												"fake message: i'll download...",
												Toast.LENGTH_SHORT).show();
									}
								})
						.setNegativeButton("no",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method stub
										Toast.makeText(
												FlowDetailActivity.this,
												"fake message: refuse download...",
												Toast.LENGTH_SHORT).show();
									}
								})
						.setOnCancelListener(
								new DialogInterface.OnCancelListener() {

									@Override
									public void onCancel(DialogInterface dialog) {
										// TODO Auto-generated method stub
										Toast.makeText(
												FlowDetailActivity.this,
												"fake message: refuse download...",
												Toast.LENGTH_SHORT).show();
									}
								}).show();
			}
		});

		WebSettings webSetting = mWebView.getSettings();
		webSetting.setAllowFileAccess(true);
		webSetting.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
		webSetting.setSupportZoom(true);
		webSetting.setBuiltInZoomControls(true);
		webSetting.setUseWideViewPort(true);
		webSetting.setSupportMultipleWindows(false);
		// webSetting.setLoadWithOverviewMode(true);
		webSetting.setAppCacheEnabled(true);
		// webSetting.setDatabaseEnabled(true);
		webSetting.setDomStorageEnabled(true);
		webSetting.setJavaScriptEnabled(true);
		webSetting.setGeolocationEnabled(true);
		webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
		webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
		webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
		webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
				.getPath());
		// webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
		webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);

		mWebView.addJavascriptInterface(new Object() {
			@JavascriptInterface
			public String getclienttype() {
				// UIHelper.ToastMessage(TodoDetailActivity.this,
				// "--getclienttype--");
				return "android";
			}

			@JavascriptInterface
			public void showDocument(String name, String url) {
				try {
					name = URLDecoder.decode(name, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				new FilePreviewUtil(context).showContent("", context);
			}

			@JavascriptInterface
			public void closeWebView() {
				// UIHelper.ToastMessage(TodoDetailActivity.this,
				// "--closeWebView--");
				// tddetailac.finish();
				finish();
				// isreturn = true;
			}

		}, "_mhy");
		
	
	}

	@Override
	public void initData() {// 必须调用
		tvBaseTitle.setText(title);
	}

	// Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

	// Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

	@Override
	public void initEvent() {// 必须调用

	}

	@Override
	public void onDragBottom(boolean rightToLeft) {
		if (rightToLeft) {
			SettingUtil.restoreDefault();
			initData();
			return;
		}

		finish();
	}

	// 系统自带监听方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

	// 类相关监听<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

	// 类相关监听>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

	// 系统自带监听方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

	// Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	private class MyWebViewDownLoadListener implements com.tencent.smtt.sdk.DownloadListener{  
		  
        @Override  
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,  
                                    long contentLength) {             
            Log.i("tag", "url="+url);             
            Log.i("tag", "userAgent="+userAgent);  
            Log.i("tag", "contentDisposition="+contentDisposition);           
            Log.i("tag", "mimetype="+mimetype);  
            Log.i("tag", "contentLength="+contentLength);  
            Uri uri = Uri.parse(url);  
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);  
            startActivity(intent);             
        }  
    }

	@Override
	public void onJsFunctionCalled(String tag) {
		showShortToast(tag);
		
	}
	private void openFileChooseProcess() {
		Intent i = new Intent(Intent.ACTION_GET_CONTENT);
		i.addCategory(Intent.CATEGORY_OPENABLE);
		i.setType("*/*");
		startActivityForResult(Intent.createChooser(i, "test"), 0);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == RESULT_OK) {
			switch (requestCode) {
				case 0:
					if (null != uploadFile) {
						Uri result = data == null || resultCode != RESULT_OK ? null
								: data.getData();
						uploadFile.onReceiveValue(result);
						uploadFile = null;
					}
					if (null != uploadFiles) {
						Uri result = data == null || resultCode != RESULT_OK ? null
								: data.getData();
						uploadFiles.onReceiveValue(new Uri[]{result});
						uploadFiles = null;
					}
					break;
				default:
					break;
			}
		} else if (resultCode == RESULT_CANCELED) {
			if (null != uploadFile) {
				uploadFile.onReceiveValue(null);
				uploadFile = null;
			}

		}
	}
//
//	/**
//	 * 确保注销配置能够被释放
//	 */
//	@Override
//	protected void onDestroy() {
//		// TODO Auto-generated method stub
//		mWebView.getSettings().setBuiltInZoomControls(true);
//		mWebView.setVisibility(View.GONE);// 把destroy()延后
//		long timeout = ViewConfiguration.getZoomControlsTimeout();
//		System.out.println("time=="+timeout);
//		new Timer().schedule(new TimerTask() {
//			@Override
//			public void run() {
//				// TODO Auto-generated method stub
//				mWebView.destroy();
//			}
//		}, timeout);
//		super.onDestroy();
//	}

	@Override
	public void onReturnClick(View v) {
		if(isLoaded){
			showShortToast("如需关闭，请点击页面上的关闭按钮！");
			mWebView.goBack();
		}else {
			finish();
		}
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		switch (keyCode) {
			case KeyEvent.KEYCODE_BACK:
				if(isLoaded){
					showShortToast("如需关闭，请点击页面上的关闭按钮！");
					mWebView.goBack();
				}else {
					finish();
				}
				return true;
		}

		return super.onKeyUp(keyCode, event);
	}
}
